<?php
/*
* +----------------------------------------------------------------------
* | SF 综合验证授权系统
* +----------------------------------------------------------------------
* | Quotes [ 花开的再灿烂，也有凋谢的一天，致我们过去的青春 ]
* +----------------------------------------------------------------------
* | Author: 陌上花开 <2129876388@qq.com>
* +----------------------------------------------------------------------
* | Date: 2022年1月19日 18:48:32
* +----------------------------------------------------------------------
*/
namespace app\common\controller;

use think\App;
use think\Exception;
use think\facade\Cache;
use think\facade\Event;
use think\facade\View;
use think\facade\Cookie;
/**
 * 系统中台控制器基类
 *
 * @author 陌上花开
 * @since 2022-01-19
 */
class UserBackend extends CommonBase
{
    // 模型
    protected $model;
    // 服务
    protected $service;
    // 校验
    protected $validate;
    // 用户ID
    protected $userId;
    // 用户登录信息
    protected $userInfo;
    protected $myAppInfo;
    protected $myPowerInfo;
    // 网络请求
    protected $param;

    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        // 初始化登录信息
        $this->initLogin();
    }


    /**
     * 校验登录
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function initLogin()
    {
        try{
            $userId = cookie('userId');
            $sign = cookie('userSign');
            $this->userId = $userId;

            // 登录用户信息
            $userModel = new \app\user\model\User();
            $userInfo = $userModel->getInfo();
            if(!empty($userId) && $sign != data_auth_sign($userInfo['appid'].$userInfo['username'].$userInfo['password'].sf_password_hash())){
                cookie('userId',null);
                cookie('userSign',null);
                throw new Exception('用户登录信息已过期，请刷新界面重新登录！');
            }
            if(!$userInfo){
                throw new Exception('您的账号异常，请联系站长处理！[errorCode:UserInfoError]');
            }
            $this->userInfo = $userInfo;
            if(empty($userInfo['appid'])){
                throw new Exception('您的账号异常，请联系站长处理！[errorCode:UserAppIdEmpty]');
            }
            if(!is_numeric($userInfo['appid']) || $userInfo['appid'] <= 0){
                throw new Exception('您的账号异常，请联系站长处理！[errorCode:UserAppIdError]');
            }
            if($userInfo['status'] != 1){
                throw new Exception('您的账号已被封禁，请联系上级处理！[errorCode:UserStatusBlocked]');
            }
            if(!empty($userInfo['ip'])){
                if(!in_array(get_client_ip(),unserialize($userInfo['ip']))){
                    throw new Exception('您当前的IP不在白名单内，请返回重新登录！');
                }
            }
            $appModel = new \app\admin\model\AppModel();
            $this->myAppInfo = $appModel->getInfo(intval($userInfo['appid']));
            if(!$this->myAppInfo){
                throw new Exception('您的账号异常，请联系站长处理！[errorCode:GetUserAppInfoError]');
            }
            $this->myPowerInfo = $this->getPowerPriceInfo(intval($userInfo['power']));
            if(!$this->myPowerInfo){
                throw new Exception('您的账号异常，请联系站长处理！[errorCode:GetUserPowerInfoError]');
            }
            // 数据绑定
            $this->userInfo['app_name'] = $this->myAppInfo['name'];
            $this->userInfo['power_name'] = $this->myPowerInfo['name'];
            $this->userInfo['addauth_discount'] = floatval($this->myPowerInfo['addauth_discount'] / 100);
            $this->userInfo['addpay_discount'] = floatval($this->myPowerInfo['addpay_discount'] / 100);
            $this->userInfo['pirate_discount'] = floatval($this->myPowerInfo['pirate_discount'] / 100);
            $this->userInfo['adduser_discount'] = floatval($this->myPowerInfo['adduser_discount'] / 100);
            View::assign('userId', $this->userId);
            View::assign('userInfo', $this->userInfo);
        }catch (\Exception $e){
            $this->logOut();
            if(IS_POST){
                exit(json_encode(message($e->getMessage(), false)));
            }
            exit($this->render('/public/error', ['msg' => $e->getMessage()]));
        }
    }

    /**
     * 退出登录
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function logOut(){
        $content = [
            'Title' => '退出登录',
            'Result' => 'success'
        ];
        event('ActionLog', $content);
        Cookie::delete('userId');
        Cookie::delete('userSign');
        Cookie::save();
        return message('退出登录成功', true);
    }

    /**
     * 判断用户是否登录
     * @return bool
     */
    public function isUserLogin()
    {
        // 用户未登录返回 false
        if (empty(cookie('userId'))) {
            return false;
        }
        // 用户已登录返回 true
        return true;
    }

    public function sendCode(){
        if(IS_POST){
            $cleartime = 180;// 过期时间 单位:秒
            $type = input('post.type');
            if(empty($type)){
                return message("缺少TYPE参数！" ,false);
            }
            $code = get_random_code(6);
            switch ($type){
                case 'changeBindingMail':
//                    if(Cache::get('changeBindingMail'.$this->userId)){
//                        return message("请勿频繁发送验证码！" ,false);
//                    }
                    if(!empty($this->userInfo['email'])){
                        $param = [
                            'to' => $this->userInfo['email'],
                            'title' => conf('title').' - 验证码通知',
                            'from_name' => conf('title'),
                            'content' => '验证码:'.$code.'。此验证码只用于更换用户账号'.$this->userInfo['username'].'的邮箱，请妥善保管，不要透露给任何人。如非本人操作请忽略。'
                        ];
                    }else{
                        $email = input('post.content');
                        if(empty($email)){
                            return message("请填写要绑定的邮箱！" ,false);
                        }
                        $param = [
                            'to' => $email,
                            'title' => conf('title').' - 验证码通知',
                            'from_name' => conf('title'),
                            'content' => '验证码:'.$code.'。此验证码只用于更换用户账号'.$this->userInfo['username'].'的邮箱，请妥善保管，不要透露给任何人。如非本人操作请忽略。'
                        ];
                    }
                    $param = !empty($this->userInfo['config'])?array_merge_recursive($param, unserialize($this->userInfo['config'])):$param;

                    Cache::set('changeBindingMail'.$this->userId, $code, $cleartime);
                    return Event::trigger('ChangeBindingMailNotice', $param)[0];
                default:
                    return message("不存在此操作！" ,false);
            }
        }
    }


    /**
     * 控制器默认入口
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/19
     */
    public function index()
    {
        return $this->render();
    }

//    /**
//     * 获取价格模板列表
//     * @return mixed
//     * @author 陌上花开
//     * @date 2022/1/25
//     */
//    public function getAuthTemplateList()
//    {
//        $authTemplateModel = new \app\admin\model\AuthTemplateModel();
//        $result = $authTemplateModel->getAllList();
//        return $result;
//    }
//
//    /**
//     * 获取权限模板列表
//     * @return mixed
//     * @author 陌上花开
//     * @date 2022/1/25
//     */
//    public function getPowerTemplateList()
//    {
//        $powerTemplateModel = new \app\admin\model\PowerTemplateModel();
//        $result = $powerTemplateModel->getAllList();
//        return $result;
//    }

//    /**
//     * 获取模式列表
//     * @return mixed
//     * @author 陌上花开
//     * @date 2022/1/25
//     */
//    public function getCheckTypeList()
//    {
//        try{
//            $checkTypeModel = new \app\admin\model\CheckTypeModel();
//            $result = $checkTypeModel->getCheckTypeList();
//            return $result;
//        }catch (\Exception $e){
//            throw new Exception($e->getMessage());
//        }
//
//    }

    /**
     * 获取价格列表
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function getAuthPriceList()
    {
        try{
            if(IS_POST){
                $appid = intval($this->userInfo['appid']);
                if(empty($appid)){
                    return message("APPID不能为空！" ,false);
                }
                $authPriceModel = new \app\admin\model\AuthPriceModel();
                $appModel = new \app\admin\model\AppModel();
                $appInfo = $appModel->getInfo($appid);
                if(!$appInfo){
                    return message("获取用户信息失败！[errorCode:GetUserAppInfoError]" ,false);
                }
                $tid = intval($appInfo['auth_template']);
                if(empty($tid)){
                    return message("获取模板ID失败！[errorCode:GetAuthPriceTIDError]" ,false);
                }
                $content = [
                    'Title' => '获取列表',
                    '操作' => '获取价格列表',
                    'Result' => 'success'
                ];
                event('ActionLog', $content);
                $result = $authPriceModel->getAuthPriceList($tid);
                return message('获取成功！',true, ['data' => $result]);
            }
        }catch (\Exception $e){
            return message("获取失败！[errorCode:GetAuthPriceList]",false);
        }
    }

//    /**
//     * 获取App列表
//     * @return array
//     * @author 陌上花开
//     * @date 2022/1/25
//     */
//    public function getAppList()
//    {
//        try{
//            $appModel = new \app\admin\model\AppModel();
//            $result = $appModel->getAllList();
//            return $result;
//        }catch (\Exception $e){
//            return message('获取应用列表失败！', false);
//        }
//
//    }

    /**
     * 获取权限信息
     * @return array
     * @author 陌上花开
     * @date 2022/1/25
     */
    private function getPowerPriceInfo($id)
    {
        if(empty($id)) return false;
        $powerPriceModel = new \app\admin\model\PowerPriceModel();
        try{
            $result = $powerPriceModel->getInfo($id);
            if(!$result) return false;
            return $result;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 获取权限列表
     * @return array
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function getPowerList(){
        $appid = intval($this->userInfo['appid']);
        try{
            $appModel = new \app\admin\model\AppModel();
            $appInfo = $appModel->getInfo($appid);
            if(!$appInfo){
                return message('获取用户应用信息失败！[errorCode:GetUserAppInfoError]' ,false);
            }
            $powerPriceModel = new \app\admin\model\PowerPriceModel();
            $result = $powerPriceModel->getAddPowerList($this->userInfo['power']);
            return message('获取列表成功！' , true, ['data' => $result]);
        } catch (\Exception $e) {
            return message('获取权限列表失败！[errorCode:GetUserAddPowerListError]',false);
        }
    }

    /**
     * 获取可升级权限列表
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function getUpdatePowerList(){
        if(IS_POST){
            try{
                $post = request()->post();
                $power = !empty($post['power'])?intval($post['power']):null;
                if(empty($power) || $power < 1){
                    return message("获取可升级权限列表失败！[errorCode:GetUpdatePowerListError]" ,false);
                }
                $powerPriceModel = new \app\admin\model\PowerPriceModel();
                $result = $powerPriceModel->getUpdatePowerList($power, $this->userInfo['power']);
                return message("获取列表成功！" ,true, ["data" => $result]);
            } catch (\Exception $e) {
                return message('获取失败！[errorCode:GetUpdatePowerListError]' ,false);
            }
        }
    }

    /**
     * 获取用户可升级权限列表
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function getUserUpdatePowerList(){
        if(IS_POST) {
            try {
                $powerPriceModel = new \app\admin\model\PowerPriceModel();
                $result = $powerPriceModel->getUserUpdatePowerList($this->userInfo['power']);
                return message('获取列表成功！', true, ['data' => $result]);
            } catch (\Exception $e) {
                return message("获取失败！[errorCode:GetUserUpdatePowerListError]", false);
            }
        }
    }
    /**
     * 添加或编辑入口
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function edit()
    {
        if (IS_POST) {
            try{
                try{
                    if(!$this->myPowerInfo) {
                        return message('获取用户权限信息失败！[errorCode:GetUserPowerInfoError]' ,false);
                    }
                    // 权限检测
                    if($this->service instanceof \app\user\service\AuthService){
                        if($this->myPowerInfo['addauth_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\PaymentService){
                        if($this->myPowerInfo['addpay_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\PirateService){
                        if($this->myPowerInfo['pirate_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\UserService){
                        if($this->myPowerInfo['adduser_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    }
                }catch (\Exception $e){
                    return message('获取访问权限失败！[errorCode:GetAccessRightsError]' ,false);
                }
                return $this->service->edit();
            }catch (\Exception $e){
                return message($e->getMessage() ,false);
            }
        }
    }

    /**
     * 删除单条记录
     * @return array
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function drop()
    {
        if (IS_POST) {
            $id = input('post.id');
            try{
                $info = $this->service->getInfo($id);
                if ($info) {
                    $this->service->drop($id);
                    return message('删除成功！', true);
                }
                return message('不存在该ID！', false);
            }catch (\Exception $e){
                return message($e->getMessage(), false);
            }
        }
    }

    /**
     * 批量删除记录
     * @return array
     * @author 陌上花开
     * @date 2019/2/25
     */
    public function batchDrop()
    {
        if (IS_POST) {
            try{
                $ids = explode(',', input('post.id'));
                //批量删除
                $num = 0;
                foreach ($ids as $key => $val) {
                    $res = $this->service->drop($val);
                    if ($res !== false) {
                        $num++;
                    }
                }
                return message('本次共选择' . count($ids) . '个条数据,删除' . $num . '个');
            }catch (\Exception $e){
                return message($e->getMessage(), false);
            }
        }
    }

    /**
     * 列表
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/12
     */
    public function list()
    {
        if (IS_POST) {
            try{
                try{
                    if(!$this->myPowerInfo) {
                        return message('获取用户权限信息失败！[errorCode:GetUserPowerInfoError]' ,false);
                    }
                    // 权限检测
                    if($this->service instanceof \app\user\service\AuthService){
                        if($this->myPowerInfo['addauth_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\PaymentService){
                        if($this->myPowerInfo['addpay_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\PirateService){
                        if($this->myPowerInfo['pirate_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    } else if ($this->service instanceof \app\user\service\UserService){
                        if($this->myPowerInfo['adduser_power'] != 1){
                            return message('无权限访问！' ,false);
                        }
                    }
                }catch (\Exception $e){
                    return message('获取访问权限失败！[errorCode:GetAccessRightsError]' ,false);
                }
                $result = $this->service->list();
                return message('获取列表成功！', true, ['data' => $result]);
            }catch (\Exception $e){
                return message($e->getMessage(), false, ['data' => []]);
            }
        }
        try{
            if(!$this->myPowerInfo) {
                return $this->render('public/error', ['msg' => '获取用户权限信息失败！[errorCode:GetUserPowerInfoError]']);
            }
            // 权限检测
            if($this->service instanceof \app\user\service\AuthService){
                if($this->myPowerInfo['addauth_power'] != 1){
                    return $this->render('public/error', ['msg' => '无权限访问！']);
                }
            } else if ($this->service instanceof \app\user\service\PaymentService){
                if($this->myPowerInfo['addpay_power'] != 1){
                    return $this->render('public/error', ['msg' => '无权限访问！']);
                }
            } else if ($this->service instanceof \app\user\service\PirateService){
                if($this->myPowerInfo['pirate_power'] != 1){
                    return $this->render('public/error', ['msg' => '无权限访问！']);
                }
                View::assign('price', round($this->myAppInfo['pirate_money'] * floatval($this->myPowerInfo['pirate_discount'] / 100), 2));
            } else if ($this->service instanceof \app\user\service\UserService){
                if($this->myPowerInfo['adduser_power'] != 1){
                    return $this->render('public/error', ['msg' => '无权限访问！']);
                }
            }
            return $this->render();
        }catch (\Exception $e){
            return $this->render('public/error', ['msg' => '获取访问权限失败！[errorCode:GetAccessRightsError]']);
        }
    }

    /**
     * 设置状态
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/12
     */
    public function setStatus()
    {
        if (IS_POST) {
            try{
                $this->service->setStatus();
                return message('更改状态成功！', true);
            }catch (\Exception $e){
                return message($e->getMessage(), false);
            }
        }
    }
}